/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.pointrepository.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.login.SysLoginUser;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.common.WdAnalysisConst;
import vip.xiaonuo.modular.pointrepository.entity.PointRepository;
import vip.xiaonuo.modular.pointrepository.enums.PointRepositoryExceptionEnum;
import vip.xiaonuo.modular.pointrepository.mapper.PointRepositoryMapper;
import vip.xiaonuo.modular.pointrepository.param.PointRepositoryParam;
import vip.xiaonuo.modular.pointrepository.service.PointRepositoryService;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 数据点仓库service接口实现类
 *
 * @author cdx
 * @date 2022-10-19 11:25:34
 */
@Service
public class PointRepositoryServiceImpl extends ServiceImpl<PointRepositoryMapper, PointRepository> implements PointRepositoryService {

    @Override
    public PageResult<PointRepository> page(PointRepositoryParam pointRepositoryParam) {
        QueryWrapper<PointRepository> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(pointRepositoryParam)) {

            // 根据数据名称 查询
            if (ObjectUtil.isNotEmpty(pointRepositoryParam.getName())) {
                queryWrapper.lambda().like(PointRepository::getName, pointRepositoryParam.getName());
            }
            // 根据地址 查询
            if (ObjectUtil.isNotEmpty(pointRepositoryParam.getAddress())) {
                queryWrapper.lambda().eq(PointRepository::getAddress, pointRepositoryParam.getAddress());
            }
            // 根据经度 查询
            if (ObjectUtil.isNotEmpty(pointRepositoryParam.getLng())) {
                queryWrapper.lambda().eq(PointRepository::getLng, pointRepositoryParam.getLng());
            }
            // 根据纬度 查询
            if (ObjectUtil.isNotEmpty(pointRepositoryParam.getLat())) {
                queryWrapper.lambda().eq(PointRepository::getLat, pointRepositoryParam.getLat());
            }
            // 根据数据处理状态 查询
            if (ObjectUtil.isNotEmpty(pointRepositoryParam.getStatus())) {
                queryWrapper.lambda().eq(PointRepository::getStatus, pointRepositoryParam.getStatus());
            }
            // 根据用户编号 查询
            if (ObjectUtil.isNotEmpty(pointRepositoryParam.getUserId())) {
                queryWrapper.lambda().eq(PointRepository::getUserId, pointRepositoryParam.getUserId());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<PointRepository> list(PointRepositoryParam pointRepositoryParam) {
        return this.list();
    }

    @Override
    public void add(PointRepositoryParam pointRepositoryParam) {
        PointRepository pointRepository = new PointRepository();
        BeanUtil.copyProperties(pointRepositoryParam, pointRepository);
        this.save(pointRepository);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<PointRepositoryParam> pointRepositoryParamList) {
        pointRepositoryParamList.forEach(pointRepositoryParam -> {
            this.removeById(pointRepositoryParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(PointRepositoryParam pointRepositoryParam) {
        PointRepository pointRepository = this.queryPointRepository(pointRepositoryParam);
        BeanUtil.copyProperties(pointRepositoryParam, pointRepository);
        this.updateById(pointRepository);
    }

    @Override
    public PointRepository detail(PointRepositoryParam pointRepositoryParam) {
        return this.queryPointRepository(pointRepositoryParam);
    }

    /**
     * 获取数据点仓库
     *
     * @author cdx
     * @date 2022-10-19 11:25:34
     */
    private PointRepository queryPointRepository(PointRepositoryParam pointRepositoryParam) {
        PointRepository pointRepository = this.getById(pointRepositoryParam.getId());
        if (ObjectUtil.isNull(pointRepository)) {
            throw new ServiceException(PointRepositoryExceptionEnum.NOT_EXIST);
        }
        return pointRepository;
    }

    @Override
    public void export(PointRepositoryParam pointRepositoryParam) {
        List<PointRepository> list = this.list(pointRepositoryParam);
        PoiUtil.exportExcelWithStream("SnowyPointRepository.xls", PointRepository.class, list);
    }

    @Override
    public void importExcel(MultipartFile file) {
        if (!(file != null && file.getOriginalFilename().endsWith(".xlsx") )) {
            throw new ServiceException(9, "请上传xlsx文件");
        }
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        Long userId = sysLoginUser.getId();
        final PointRepositoryService that = this;
        try {
            EasyExcel.read(file.getInputStream(), PointRepository.class, new ReadListener<PointRepository>() {
                ArrayList<PointRepository> list = new ArrayList<>();
                @Override
                public void invoke(PointRepository pointRepository, AnalysisContext analysisContext) {
                    list.add(pointRepository);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    for (PointRepository p : list) {
                        p.setUserId(userId);
                        p.setStatus("1");
                        p.setUpdateTime(new Date());
                        if (p.getLng() == null || p.getLat() == null) {
                            fillLngLat(p);
                        }
                        int count = that.count(new LambdaQueryWrapper<PointRepository>().eq(PointRepository::getAddress, p.getAddress()));
                        if (count > 0) {
                            continue;
                        }
                        that.save(p);
                    }
                }
            }).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void fillLngLat(PointRepository pointRepository) {
        // 调用高德api接口将地址转码成经纬度
        String url = WdAnalysisConst.AMAP_GEOCODE_URL;
        Map<String, Object> p = new HashMap<>();
        p.put("key", WdAnalysisConst.AMAP_KEY);
        boolean updateAddressFlag = false;
        if(StringUtils.hasText(pointRepository.getAddress())){
            p.put("address", pointRepository.getAddress());
        }else if(StringUtils.hasText(pointRepository.getName())){
            updateAddressFlag = true;
            p.put("address", pointRepository.getName());
        }else{
            return;
        }
        String s = HttpUtil.get(url, p);
        JSONArray geocodes = JSONObject.parseObject(s).getJSONArray("geocodes");
        if (geocodes != null && geocodes.size() > 0) {
            String location = geocodes.getJSONObject(0).getString("location");
            pointRepository.setLng(new BigDecimal(location.split(",")[0]));
            pointRepository.setLat(new BigDecimal(location.split(",")[1]));
            if (updateAddressFlag) {
                pointRepository.setAddress(geocodes.getJSONObject(0).getString("formatted_address"));
            }
        }
    }
}
